/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo;

import clases.Serie;
import clases.TipoComprobante;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author root
 */
public class MdlSerie implements Modelo<Serie>{

    /**
     * 
     * @param serie
     * @param cnx
     * @throws SQLException 
     */
    @Override
    public void insert(Serie serie, Conexion cnx) throws SQLException {
        String sql = "INSERT INTO serie(tipoComprobante, nombre) "
                + "VALUES(" + serie.getTipoComprobante().getIdTipoComprobante() +", "
                + "'" + serie.getNombre() + "')";
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public int getLastId(Conexion cnx) throws SQLException {
        String sql = "SELECT MAX(idSerie) FROM serie;";
        ResultSet rs = cnx.consultar(sql);
        if (rs.next()) {
            return rs.getInt(1);
        }
        return -1;
    }

    @Override
    public void update(Serie serie, Conexion cnx) throws SQLException {
        String sql = "UPDATE serie SET "
                + "tipoComprobante = " + serie.getTipoComprobante().getIdTipoComprobante() + ", "
                + "nombre = '" + serie.getNombre() + "' "
                + "WHERE idSerie = " + serie.getIdSerie();
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param query
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public ArrayList<Serie> get(String query, Conexion cnx) throws SQLException {
        ResultSet rs = cnx.consultar(query);
        ArrayList<Serie> series = new ArrayList();
        while(rs.next()){
            series.add(new Serie(
                    rs.getInt(1),
                    new TipoComprobante(){
                        {
                            this.setIdTipoComprobante(rs.getInt(2));
                        }
                    },
                    rs.getString(3)
            ));
        }
        return series;
    }

    /**
     * 
     * @param id
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public Serie get(int id, Conexion cnx) throws SQLException {
       String sql = "SELECT * FROM serie WHERE idSerie = " + id;
       ResultSet rs = cnx.consultar(sql);
       Serie serie = null;
        if (rs.next()) {
            serie = new Serie(
                    rs.getInt(1),
                    new TipoComprobante(){
                        {
                            this.setIdTipoComprobante(rs.getInt(2));
                        }
                    },
                    rs.getString(3)
            );
        }
        return serie;
    }
    
}
